import FightTouchView from "./FightTouchView";
import MapConfig from "../Config/MapConfig";
import GameMap from "../Map/GameMap";
import { GameManager } from "../GameManager";
import MonsterView from "./MonsterView";
import Monster from "../Monster/Monster";

const { ccclass, property } = cc._decorator;

@ccclass
export default class MapView extends cc.Component {

    @property(cc.Node)
    player_node: cc.Node = null;

    @property(cc.TiledMap)
    tiledMap: cc.TiledMap = null;

    @property(FightTouchView)
    fight_touch: FightTouchView = null;

    @property(cc.Prefab)
    monster_prefab: cc.Prefab = null;

    obsLayer: cc.TiledLayer = null;
    activeLayer: cc.TiledObjectGroup = null;
    tileds: Array<cc.TiledTile> = [];
    monsters: Array<MonsterView> = [];

    m_map: GameMap = null;

    // layerWidth: number = 0;
    // layerHeight: number = 0;
    // tiledWidth: number = 0;
    // tiledHeight: number = 0;


    onLoad() {

    }

    public init(map: GameMap): void {
        if (!map || this.m_map && this.m_map.m_mapId == map.m_mapId) {
            return;
        }

        this.tileds = [];
        this.monsters = [];

        this.player_node.parent = this.node;

        if (this.tiledMap.tmxAsset) {
            //this.tiledMap.tmxAsset.decRef();
            this.tiledMap.tmxAsset = null;
        }

        this.m_map = map;
        this.m_map.m_monsterMg.m_mapView = this;

        //动态加载地图
        let resName = `./tmx/map_${map.m_mapId}`;
        let self = this;
        cc.resources.load(resName, cc.TiledMapAsset, (err, asset) => {
            if (!err) {
                self.tiledMap.tmxAsset = <cc.TiledMapAsset>asset;
                self.tiledMap.tmxAsset.addRef();
                self.obsLayer = self.tiledMap.getLayer("obstacle");

                self.activeLayer = self.tiledMap.getObjectGroup("active");
                self.player_node.parent = self.activeLayer.node;
                self.player_node.setPosition(cc.v2(0, 0));
                self.fight_touch.root_node = self.activeLayer.node;

                self.initMapLayer();
                self.initMonster();
            }
        });
    }

    public initMapLayer(): void {

        let tiledSize = this.obsLayer.getMapTileSize();
        let layerSize = this.obsLayer.getLayerSize();

        for (let i = 0; i < layerSize.width; i++) {
            for (let j = 0; j < layerSize.height; j++) {
                let tiled = this.obsLayer.getTiledTileAt(i, j, true);
                if (tiled.gid != 0) {
                    tiled.node.group = "obstacle";
                    let body = tiled.node.addComponent(cc.RigidBody);
                    body.type = cc.RigidBodyType.Static;
                    let collider = tiled.node.addComponent(cc.PhysicsBoxCollider);
                    collider.offset = cc.v2(tiledSize.width / 2, tiledSize.height / 2);
                    collider.size = tiledSize;
                    collider.apply();
                }
                else{
                    this.tileds.push(tiled);
                }
            }
        }
    }

    public initMonster(): void {
        this.m_map.m_monsterMg.m_monsters.forEach((monster, key) => {
            let node = cc.instantiate(this.monster_prefab);
            let pos = this.randomPos();
            node.setPosition(pos);
            node.parent = this.activeLayer.node;
            let mView = node.getComponent(MonsterView);
            mView.init(monster);
            
            this.monsters.push(mView);
        });
    }

    private randomPos(): cc.Vec2 {
        let tiled = this.tileds[this.randomInt(0, this.tileds.length)];
        let w_pos = this.obsLayer.node.convertToWorldSpaceAR(tiled.node.getPosition());
        let n_pos = this.activeLayer.node.convertToNodeSpaceAR(w_pos);

        //限制用户移动在地图内
        let size = this.activeLayer.node.getContentSize();
        let maxH = size.height / 2 - 30;
        let maxW = size.width / 2 - 30;
        n_pos.x = Math.abs(n_pos.x) > maxW ? (n_pos.x > 0 ? maxW : -maxW) : n_pos.x;
        n_pos.y = Math.abs(n_pos.y) > maxH ? (n_pos.y > 0 ? maxH : -maxH) : n_pos.y;

        return n_pos;
    }

    private randomInt(n: number, m: number): number {
        return Math.round(Math.random() * (m - n));
    }

    //怪物移除
    public onRemoveMonster(monster: Monster):void{
        for(let i = 0; i < this.monsters.length; ++i){
            if(this.monsters[i].m_monster === monster){
                this.monsters[i].onDead();
                this.monsters[i].node.removeFromParent(true);
                this.monsters.splice(i, 1);
                break;
            }
        }
    }

    // //地图节点坐标转tiled坐标
    // private nodeToTiledPoint(nodePoint: cc.Vec2): cc.Vec2 {
    //     //tiled坐标是已左上角为原点
    //     let n_x = this.layerWidth / 2 + nodePoint.x;
    //     let n_y = this.layerHeight / 2 - nodePoint.y;
    //     let t_x = n_x == 0 ? 0 : Math.ceil(n_x / this.tiledWidth)-1;
    //     let t_y = n_y == 0 ? 0 : Math.ceil(n_y / this.tiledHeight)-1;
    //     return new cc.Vec2(t_x, t_y);
    // }

    //tiled坐标转节点坐标
    // private tiledToNodePoint(tiledPoint: cc.Vec2): cc.Vec2{
    //     let tiledSize = this.obsLayer.getMapTileSize();
    //     let layerSize = this.obsLayer.getLayerSize();
    //     // let tmp_pos = this.obsLayer.getPositionAt(tiledPoint);
    //     let n_x = tiledPoint.x * tiledSize.width + tiledSize.width / 2 - layerSize.width / 2;
    //     let n_y =  layerSize.height  / 2 - tiledPoint.y * tiledSize.height + tiledSize.height  / 2;
    //     return cc.v2(n_x, n_y);
    // }
}
